package cn.kgc.gmall.app.dwm;

import cn.kgc.gmall.utils.MyKafkaUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * 语义化 见名知意
 * 用户跳出行为: 读取dwd_topic_page
 *
 */
public class UserJumpDetailApp {
    public static void main(String[] args) throws Exception {

        // 1. 运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度
        env.setParallelism(4);
        // 2. 检查点相关设置
        // 3.设置检查点 精准一次
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);

        // 4.检查点启动时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        // 4.1 如果flink程序关闭是否删除检查点
        env.getCheckpointConfig()
                .enableExternalizedCheckpoints(
                        CheckpointConfig
                                .ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
                );
        // 5.状态后端保存检查点到hdfs上
        env.setStateBackend(new FsStateBackend("hdfs://hadoop102:8020/gmall/flink/checkpoint"));
        // 6.设置用户
        System.setProperty("HADOOP_USER_NAME","atkgc");
        // 略 ...
        // 3. 读取kafka中的数据
        String topic = "dwd_topic_page";
        String group = "page_jump_group";
        DataStreamSource<String> pageDS = env.addSource(MyKafkaUtils.getKafkaConsumerSource(topic, group));
        // 测试数据
        /*DataStream<String> pageDS = env
                .fromElements(
                        "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":12000}",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"home\"},\"ts\":15000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"detail\"},\"ts\":30000} "
                );*/

        // 将字符串转化为jsonObject
        SingleOutputStreamOperator<JSONObject> mapDS = pageDS.map(JSON::parseObject);

        // 设置水位线
        SingleOutputStreamOperator<JSONObject> watermarksDS = mapDS.assignTimestampsAndWatermarks(
                WatermarkStrategy.
                        <JSONObject>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject jsonObj, long recordTimestamp) {
                                return jsonObj.getLong("ts");
                            }
                        })
        );
        // 进行分组
        KeyedStream<JSONObject, String> keyByDS = watermarksDS.keyBy(x -> x.getJSONObject("common").getString("mid"));

        // 匹配条件: 1.last_page_id 为 null  证明是首次访问
        // 4. 编写pattern
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("first").where(
                new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) {
                        String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        if (lastPageId != null && lastPageId.length() > 0) {
                            return false;
                        }
                        return true;
                    }
                }
                // 只要是10秒内进行了下一次操作 那么这个操作就是一个进一步访问行为不是跳出行为
        ).next("second").where(
                new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) {
                        String pageId = jsonObj.getJSONObject("page").getString("page_id");
                        if (pageId != null && pageId.length() > 0) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        ).within(Time.seconds(10L));

        // 5. 匹配流程
        PatternStream<JSONObject> patternStream = CEP.pattern(keyByDS, pattern);

        // 定义侧输出流
        OutputTag<String> jump_page = new OutputTag<String>("jump_page"){};
        // 6. 取出超时的数据,侧输出流中的数据
        SingleOutputStreamOperator<String> resultDS = patternStream.flatSelect(
                jump_page,
                new PatternFlatTimeoutFunction<JSONObject, String>() {
                    @Override
                    public void timeout(Map<String, List<JSONObject>> pattern, long timeoutTimestamp, Collector<String> out) throws Exception {
                        //获取跳出是数据
                        List<JSONObject> first = pattern.get("first");
                        // 遍历
                        for (JSONObject jsonObject : first) {
                            out.collect(jsonObject.toJSONString());// 向下游传递
                        }
                    }
                },
                new PatternFlatSelectFunction<JSONObject, String>() {
                    @Override
                    public void flatSelect(Map<String, List<JSONObject>> pattern, Collector<String> out) throws Exception {

                    }
                }
        );
        // 获取侧输出流
        DataStream<String> sideOutput = resultDS.getSideOutput(jump_page);


        /*patternStream.select(
                jump_page,
                new PatternTimeoutFunction<JSONObject, String>() {
                    @Override
                    public String timeout(Map<String, List<JSONObject>> pattern, long timeoutTimestamp) throws Exception {
                        return null;
                    }
                },
                new PatternSelectFunction<JSONObject, String>() {
                    @Override
                    public String select(Map<String, List<JSONObject>> pattern) throws Exception {
                        return null;
                    }
                }
        )*/

        // 7. 写出到kafka
        sideOutput.addSink(MyKafkaUtils.getKafkaProducerSink("dwm_user_jump_detail"));


        env.execute();

    }
    /*public static class Myextends PatternProcessFunction<IN, OUT> implements TimedOutPartialMatchHandler<IN>{

    }*/
}
